import java.util.Random;


/**
 * A card deck for playing the game Sorry!
 * With methods for shuffling, drawing and discarding from the deck.
 * @author Melissa
 */
public class Cards
{
    private int[] deck;
    private int top;

    /**
     * Builds and shuffles a deck of cards with 5 1's and 4 of each of the
     * following: 2, 3, 4, 5, 7, 8, 10, 11, 12, Sorry
     */
    public Cards()
    {
        deck = new int[45];
        top = 0;
        int i = 0;

        while(i < 5)
        {
            deck[i] = 1;
            i++;
        }
        while(i < 9)
        {
            deck[i] = 2;
            i++;
        }
        while(i < 13)
        {
            deck[i] = 3;
            i++;
        }
        while(i < 17)
        {
            deck[i] = 4;
            i++;
        }
        while(i < 21)
        {
            deck[i] = 5;
            i++;
        }
        while(i < 25)
        {
            deck[i] = 7;
            i++;
        }
        while(i < 29)
        {
            deck[i] = 8;
            i++;
        }
        while(i < 33)
        {
            deck[i] = 10;
            i++;
        }
        while(i < 37)
        {
            deck[i] = 11;
            i++;
        }
        while(i < 41)
        {
            deck[i] = 12;
            i++;
        }
        while(i < 45)
        {
            deck[i] = 13; // Sorry cards
            i++;
        }
        shuffle();
    }

    /**
     * Shuffles deck by swapping each card with a random card in the deck
     */
    public void shuffle()
    {
        int temp;
        int randomNum;
        Random gen = new Random();

        for (int i = 0; i < deck.length; i++)
        {
            randomNum = Math.abs(gen.nextInt()) % 45;
            temp = deck[i];
            deck[i] = deck[randomNum];
            deck[randomNum] = temp;
        }
    }

    /**
     * Discards the top card.
     * Reshuffles when the end of the deck is reached.
     */
    public void discard()
    {
        if (top < 44)
            top++;
        else
        {
            shuffle();
            top = 0;
        }
    }

    /**
     * Returns the card at the top of the deck, and discards it.
     * @return top card
     */
    public int drawTopCard()
    {
        int card = deck[top];
        discard();
        return card;
    }
}
